package br.com.pnfp.web.control.utils;

import java.io.UnsupportedEncodingException;

import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
/**
 * 
 * @author andrew.lima
 *
 */
public class CriptoDES {
	/**
	 * ecipher.
	 */
	private static Cipher ecipher;
	/**
	 * dcipher.
	 */
	private static Cipher dcipher;
	/**
	 * 
	 * @param chave String
	 */
	public CriptoDES() {
		byte[] rawkey = hexBytes("5446615264454F49");
		SecretKey key = new SecretKeySpec(rawkey, "DES");
		try {
			ecipher = Cipher.getInstance("DES");
			dcipher = Cipher.getInstance("DES");
			ecipher.init(Cipher.ENCRYPT_MODE, key);
			dcipher.init(Cipher.DECRYPT_MODE, key);

		} catch (javax.crypto.NoSuchPaddingException e) {
		} catch (java.security.NoSuchAlgorithmException e) {
		} catch (java.security.InvalidKeyException e) {
		}
	}
	/**
	 * 
	 * @param str String
	 * @return null
	 */
	public final String encrypt(final String str) {
		try {

			byte[] iso = str.getBytes("ISO-8859-1");
			byte[] enc = ecipher.doFinal(iso);
			return new Base64().encodeToString(enc);
		} catch (javax.crypto.BadPaddingException e) {
		} catch (IllegalBlockSizeException e) {
		} catch (UnsupportedEncodingException e) {
		}
		return null;
	}
	/**
	 * 
	 * @param str String
	 * @return null
	 */
	public final String decrypt(final String str) {
		try {
			byte[] dec = new Base64().decode(str);
			byte[] iso = dcipher.doFinal(dec);
			return new String(iso, "ISO-8859-1");
		} catch (javax.crypto.BadPaddingException e) {
		} catch (IllegalBlockSizeException e) {
		} catch (UnsupportedEncodingException e) {
		}
		return null;
	}
	/**
	 * 
	 * @param hexText String
	 * @return rawToByte
	 */
	public static byte[] hexBytes(final String hexText) {

		String chunk = null;

		int numBytes = hexText.length() / 2;

		byte[] rawToByte = new byte[numBytes];
		int offset = 0;
		for (int i = 0; i < numBytes; i++) {
			chunk = hexText.substring(offset, offset + 2);
			offset += 2;
			rawToByte[i] = (byte) (Integer.parseInt(chunk, 16));
		}
		return rawToByte;
	}

}
